<template>
  <view>
    <view @tap.stop="openSelect" class="color-CCCCCC flex align-center">
      <text :class="{'isShow':show}" class="animate text-ellipsis">{{ showLabel }}</text>
      <view :class="{'isShow':show}" style="padding-left:6rpx;padding-right:6rpx" >
        <u-icon class="arrow" :class="{'rotate180':show}" name="arrow-down-fill" size="12"></u-icon>
      </view>
    </view>
    <u-select
      mode="single-column"
      v-model="show"
      :list="list"
      :value-name="valueKey"
      :label-name="label"
      :default-value="defaultIndex"
      @confirm="confirm"
      @cancel="cancel"
    />
  </view>
</template>

<script>
/**
 * @description: 带箭头且文本颜色改变的下拉选择器
 * @property {String} placeholder 提示语
 * @property {Array} list 数据列表
 * @property {String} label 自定义数据标签
 * @property {String} valueKey 自定义数据关键Id
 * @property {string} value 当前选中的值
 * @property {bool} show 下拉框控制展示
 * @property {string} defaultKeyValue 指定下拉框的默认值对应的 valueKey
 * @property {bool} closeInit 选择框 点击取消是否重置选项，默认 true
 * @events {Function} openSelect 打开选择框
 * @events {Function} confirm 确认选择数据回调通知
 * @events {Function} cancel 清空当前选中的值
 * @example:
 * <DropDownSelect
 * placeholder="选择医院"
 * :list="list"
 * valueKey="id"
 * @confirm="confirm"
 * />
 */

export default {
  name: "DropDownSelect",
  props: {
    placeholder:{
      type: String,
      default: '选择'
    },
    list:{
      type: Array,
      default : function(){
        return []
      }
    },
    label :{
      type: String,
      default : 'name'
    },
    valueKey:{
      type: String,
      default: 'value'
    },
    defaultKeyValue:{
      type: String,
      default: ''
    },
    closeInit:{
      type: Boolean,
      default:true
    }
  },
  watch:{
    defaultKeyValue(newVal, oldVal){
      this.value = newVal
    }
  },
  data(){
    return {
      value:'',
      show:false,
      defaultIndex: [0]
    }
  },
  computed: {
    //选择的Id值转化为标签
    showLabel() {
      const r = this.list.find(item => item[this.valueKey] === this.value)
      return r != undefined && r ? r[this.label] : this.placeholder
    },
  },
  methods: {
    //弹框打开
    openSelect(){
      this.show = true
    },
    //数据确认
    confirm([data]){
      this.value = data.value
      const idx = this.list.findIndex(el => el[this.valueKey] === this.value)
      if(idx !== -1){
        this.defaultIndex = [idx]
      }
      this.$emit('confirm', data.value)
    },
    cancel([data]){
      if(this.closeInit){
        this.value = ''
        this.defaultIndex = [0]
        this.$emit('confirm', '')
      }
    }
  },
}
</script>

<style scoped lang="scss">
.isShow {
  color: #2D8CF0 !important;
  *{
    color: #2D8CF0 !important;
  }
}
.rotate180{
  transform: rotate(180deg) scale(.7) !important;
}
.arrow{
  transform: rotate(0) scale(.7);
  transition: all 0.2s;
}
.animate{
  transition: all 0.3s;
}
</style>